package com.sec.android.app.myfiles.module.download.providerapps;

import android.app.DownloadManager;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.net.Uri;

import com.sec.android.app.myfiles.dialog.ConfirmOmaDialog;
import com.sec.android.app.myfiles.info.MediaFile;
import com.sec.android.app.myfiles.log.Log;
import com.sec.android.app.myfiles.module.abstraction.AbsProviderImp;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.module.download.DownloadFileRecord.DownloadType;
import com.sec.android.app.myfiles.provider.DbTableInfo.COLUMN_ID;
import com.sec.android.app.myfiles.util.PreferenceUtils;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;

public class BrowserProviderImp extends AbsSupportAppProviderImp {
    private static final String FILE_URI_HEADER = "file://";
    private static final String S_BROWSER_PACKAGE_NAME = "com.sec.android.app.sbrowser";
    private static final String NOTIFICATION_PACKAGE = "notificationpackage";
    private int mFileIdIndex;
    private int mPathIndex;
    private int mDateIndex;
    private int mSourceIndex;
    private int mStatusIndex;
    private int mMimeTypeIndex;

    public BrowserProviderImp(Context context, AbsProviderImp provider, SQLiteDatabase db) {
        super(context, provider, db);
    }

    private boolean needRefresh() {
        boolean bRet = false;

        ArrayList<Integer> browserList = new ArrayList<>();
        ArrayList<Integer> browserStatus = new ArrayList<>();

        try (Cursor c = getCursor()) {
            if (c != null) {
                mFileIdIndex = c.getColumnIndexOrThrow(DownloadManager.COLUMN_ID);
                mStatusIndex = c.getColumnIndex(DownloadManager.COLUMN_STATUS);

                PreferenceUtils.setSupportNotificationPackage(mContext, c.getColumnIndex(NOTIFICATION_PACKAGE));
                if (c.moveToFirst()) {
                    do {
                        Integer id = c.getInt(mFileIdIndex);
                        Integer status = c.getInt(mStatusIndex);
                        browserList.add(id);
                        browserStatus.add(status);
                    } while (c.moveToNext());
                }
            }
        }

        try (Cursor c = getDownloadList()) {
            if (c != null) {
                if (c.moveToFirst()) {
                    do {
                        int index = browserList.indexOf(c.getInt(0));
                        if (index < 0) {
                            // check id not is exist
                            bRet = true;
                        } else if (browserStatus.get(index) != c.getInt(1)) {
                            // check status is not same
                            bRet = true;
                        }

                        //Log.d(this, "Status is " + browserStatus.get(index) + ":" + c.getInt(1));

                        if (!bRet) {
                            browserList.remove(index);
                            browserStatus.remove(index);
                        } else {
                            break;
                        }
                    } while (c.moveToNext());
                }
            }
        }

        if (!browserList.isEmpty()) {
            Log.d(this, "needRefresh() : browserList is not empty");
            bRet = true;
        }

        Log.d(this, "needRefresh() : ret = " + bRet);

        return bRet;

    }

    private Cursor getDownloadList() {
        final String where = mTableInfo.getColumnName(COLUMN_ID.DOWNLOAD_BY) + "=" + DownloadType.DOWNLOAD_BY_BROWSER.ordinal();
        return mDB.query(mTableInfo.getTableName(), new String[]{
                mTableInfo.getColumnName(COLUMN_ID.DOWNLOAD_ID), mTableInfo.getColumnName(COLUMN_ID.STATUS)}, where, null, null, null, null);

    }

    @Override
    protected void _refresh(Uri uri) {
        if (needRefresh()) {
            clearDB();
            super._refresh(uri);
        }
    }

    public void refreshForce(Uri uri) {
        // Because DB is updated, do not check needRefresh() and just call _refresh
        clearDB();
        super._refresh(uri);
    }

    @Override
    protected Cursor getCursor() {
        Cursor ret = null;
        DownloadManager dm = (DownloadManager) mContext.getSystemService(Context.DOWNLOAD_SERVICE);
        DownloadManager.Query query = new DownloadManager.Query();

        try {
            ret = dm.query(query);
        } catch (SQLiteException e) {
            Log.e(this, e.getMessage());
        }
        return ret;
    }

    private void clearDB() {
        final String where = mTableInfo.getColumnName(COLUMN_ID.DOWNLOAD_BY) + "=" + DownloadType.DOWNLOAD_BY_BROWSER.ordinal();
        mDB.delete(mTableInfo.getTableName(), where, null);
    }

    private String trimFilePath(String path) {
        // Because we use COLUMN_LOCAL_URI not to use deprecated API, fullPath starts with "file://",
        // so we have to remove it.
        return path.replace(FILE_URI_HEADER, "");
    }

    @Override
    protected ContentValues getContentValues(Cursor c) {
        ContentValues ret = new ContentValues();

        int downloadId = c.getInt(mFileIdIndex);
        try {
            String rawPath = c.getString(mPathIndex);
            if (rawPath == null) {
                return null;
            }
            String fullPath = trimFilePath(java.net.URLDecoder.decode(rawPath, "UTF-8"));
            if (fullPath == null) {
                return null;
            }

            String path = FileRecord.getPath(fullPath);
            String name = FileRecord.getName(fullPath);

            int fileType = MediaFile.getFileType(fullPath, mContext);
            long date = c.getLong(mDateIndex);
            String source = c.getString(mSourceIndex);
            String extension = FileRecord.getExt(name);

            int status = c.getInt(mStatusIndex);
            long size;
            String mimeType;
            String description;

            //TODO HYL Download
            /*if (status == DownloadManager.SEM_STATUS_OMA_PENDING) {
                name = c.getString(c.getColumnIndex(DownloadManager.SEM_COLUMN_DD_FILE_NAME));
                size = c.getLong(c.getColumnIndex(DownloadManager.SEM_COLUMN_DD_CONTENT_SIZE));
                mimeType = c.getString(mMimeTypeIndex);
                description = c.getString(c.getColumnIndex(DownloadManager.SEM_COLUMN_DD_FILE_DESCRIPTION));

                ConfirmOmaDialog.sArgs.putString("dm_file_oldPath", fullPath);
            } else { */
                if (name == null) {
                    name = c.getString(c.getColumnIndex(DownloadManager.COLUMN_TITLE));
                }
                size = c.getLong(c.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
                mimeType = c.getString(mMimeTypeIndex);
                description = c.getString(c.getColumnIndex(DownloadManager.COLUMN_DESCRIPTION));
            //}

            int notificationPackageIdx = c.getColumnIndex(NOTIFICATION_PACKAGE);
            if (notificationPackageIdx != -1) {
                String notificationPackageName = c.getString(notificationPackageIdx);
                if (S_BROWSER_PACKAGE_NAME.equalsIgnoreCase(notificationPackageName)) {
                    ret.put(COL_FromSBrowser, true);
                }
            }
            ret.put(COL_DownloadId, downloadId);
            ret.put(COL_Name, name);
            ret.put(COL_FileType, fileType);
            ret.put(COL_Size, (size < 0) ? 0 : size);
            ret.put(COL_Date, date);
            ret.put(COL_Path, path);
            ret.put(COL_Ext, extension);
            ret.put(COL_MimeType, mimeType);
            ret.put(COL_Source, source);
            ret.put(COL_Description, description);
            ret.put(COL_Status, status);
            ret.put(COL_DownloadBy, DownloadType.DOWNLOAD_BY_BROWSER.ordinal());
        } catch (UnsupportedEncodingException e) {
            Log.e(this, "UnsupportedEncodingException:" + e.toString());
            ret = null;
        }

        return ret;
    }

    @Override
    protected void setColumnIndex(Cursor cursor) {
        mFileIdIndex = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_ID);
        mPathIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
        mDateIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LAST_MODIFIED_TIMESTAMP);
        mSourceIndex = cursor.getColumnIndex(DownloadManager.COLUMN_URI);
        mStatusIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS);
    }

    @Override
    protected boolean needClearUnnecessaryData() {
        return false;
    }

    @Override
    protected DownloadType getDownloadType() {
        return DownloadType.DOWNLOAD_BY_BROWSER;
    }

}
